package com.zhangfb95.crosschain.plugin.container.java.fabric2.timer;

import com.zhangfb95.crosschain.plugin.container.java.fabric2.infra.config.properties.FabricProperties;
import com.zhangfb95.crosschain.plugin.container.java.fabric2.service.ChaincodeEventService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangfubing
 * @since 2024/1/9
 */
@Slf4j
@Component
public class ChaincodeEventTimer {

    @Autowired
    private FabricProperties fabricProperties;
    @Autowired
    private ChaincodeEventService chaincodeEventService;

    @PostConstruct
    public void init() {
        initChaincodeEventTimer();
    }

    public void initChaincodeEventTimer() {
        // 是否启用
        Boolean enable = fabricProperties.getChaincodeEvent().getEnable();
        if (enable == null || !enable) {
            return;
        }

        Thread registerEventThread = new Thread(() -> {
            start(chaincodeEventService::registerEvent);
        });
        registerEventThread.start();

        Thread syncThread = new Thread(() -> {
            start(chaincodeEventService::startSync);
        });
        syncThread.start();

        Thread retryThread = new Thread(() -> {
            start(chaincodeEventService::startRetry);
        });
        retryThread.start();
    }

    private void start(Runnable runnable) {
        while (true) {
            try {
                runnable.run();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}
